{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import, division, print_function, unicode_literals\n",
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Train on 60000 samples\n",
      "Epoch 1/5\n",
      "60000/60000 [==============================] - 3s 54us/sample - loss: 0.2936 - accuracy: 0.9150\n",
      "Epoch 2/5\n",
      "60000/60000 [==============================] - 3s 48us/sample - loss: 0.1411 - accuracy: 0.9580\n",
      "Epoch 3/5\n",
      "60000/60000 [==============================] - 3s 48us/sample - loss: 0.1056 - accuracy: 0.9676\n",
      "Epoch 4/5\n",
      "60000/60000 [==============================] - 3s 47us/sample - loss: 0.0859 - accuracy: 0.9737\n",
      "Epoch 5/5\n",
      "60000/60000 [==============================] - 3s 47us/sample - loss: 0.0768 - accuracy: 0.9757\n",
      "10000/10000 - 0s - loss: 0.0730 - accuracy: 0.9779\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[0.07302548268847167, 0.9779]"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 加载数据集\n",
    "mnist = tf.keras.datasets.mnist\n",
    "\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "x_train, x_test = x_train / 255.0, x_test / 255.0\n",
    "\n",
    "# 搭建 tf.keras.Sequential 模型。为训练选择优化器和损失函数\n",
    "model = tf.keras.models.Sequential([\n",
    "  tf.keras.layers.Flatten(input_shape=(28, 28)),\n",
    "  tf.keras.layers.Dense(128, activation='relu'),\n",
    "  tf.keras.layers.Dropout(0.2),\n",
    "  tf.keras.layers.Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "model.compile(optimizer='adam',\n",
    "              loss='sparse_categorical_crossentropy',\n",
    "              metrics=['accuracy'])\n",
    "\n",
    "# 训练并验证模型\n",
    "model.fit(x_train, y_train, epochs=5)\n",
    "\n",
    "model.evaluate(x_test,  y_test, verbose=2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6rc1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
